import {Button, message, Pagination, Space, Table, Tag, Tooltip} from "antd";
import TaskSearch from "../../../components/console/task/taskSearch";
import {useEffect, useState} from "react";
import RequestUtils from "../../../utils/requestUtils";
import RequestApis from "../../../apis/requestApis";
import {EditOutlined, EyeOutlined, PlusCircleOutlined} from "@ant-design/icons";
import TaskCreate from "../../../components/console/task/taskCreate";
import {useNavigate} from "react-router-dom";

/**
 * 定时任务页面
 * @returns {JSX.Element}
 * @constructor
 */
const ConsoleTaskPage = () => {

    const navigate = useNavigate();
    const [messageApi, contextHolder] = message.useMessage();

    // 创建定时任务模态框开关
    const [createTaskVisible, setCreateTaskVisible] = useState(false);

    // 分页查询条件
    const [paginationReq, setPaginationReq] = useState({
        pageNum: 1,
        pageSize: 10
    });

    // 定时任务查询条件
    const [pageQueryTaskReq, setPageQueryTaskReq] = useState({
        // 任务名称
        taskName: '',
        // 服务名称
        serviceName: '',
        // 定时任务回调地址
        uri: ''
    });

    // 分页查询定时任务返回结果
    const [pageQueryTaskResp, setPageQueryTaskResp] = useState({
        total: 0,
        pageCount: 0,
        records: []
    });

    // 定义状态样式配置
    const statusConfig = {
        // 任务执行状态配置
        executeStatus: {
            '未执行': {color: '#8c8c8c', bgColor: '#f5f5f5', icon: '⏳'},
            '执行中': {color: '#1890ff', bgColor: '#e6f7ff', icon: '🔄', isSpin: true},
            '执行成功': {color: '#52c41a', bgColor: '#f6ffed', icon: '✅'},
            '执行失败': {color: '#ff4d4f', bgColor: '#fff2f0', icon: '❌'}
        },
        // 开启状态配置
        startStatus: {
            '是': {color: '#00b42a', bgColor: '#e8fff3', icon: '🟢'},
            '否': {color: '#ff7a45', bgColor: '#fff7e6', icon: '🔴'}
        }
    };

    // 定义通用标签样式
    const baseTagStyle = {
        borderRadius: '16px',
        padding: '4px 12px',
        fontSize: '13px',
        fontWeight: 500,
        display: 'inline-flex',
        alignItems: 'center',
        gap: '6px',
        transition: 'all 0.2s ease'
    };

    // 定义分页查询列表展示字段（仅调整顺序，核心字段前置）
    const pageQueryTaskRespFields = [
        {
            title: "序号",
            key: "index",
            width: 80,
            fixed: 'left',
            align: 'center',
            render: (text, record, index) => {
                return (
                    <div style={{
                        width: '100%',
                        height: '100%',
                        display: 'flex',
                        alignItems: 'center',
                        justifyContent: 'center',
                        color: '#666',
                        fontWeight: 500,
                        fontSize: '13px'
                    }}>
                        {(paginationReq.pageNum - 1) * paginationReq.pageSize + index + 1}
                    </div>
                )
            },
            isShow: true
        }, {
            title: "任务名称",
            dataIndex: 'taskName',
            key: 'taskName',
            width: 180,
            fixed: 'left',
            align: 'center',
            isShow: true,
            render: (text, record) => (
                <div style={{
                    color: '#1890ff',
                    fontWeight: 600,
                    fontSize: '14px',
                    transition: 'color 0.2s ease',
                    cursor: 'pointer',
                }}
                     onClick={() => redirect2TaskDetail("search", record.id)}
                >
                    {text}
                </div>
            )
        }, {
            title: "任务描述",
            dataIndex: "taskDescription",
            key: "taskDescription",
            width: 220,
            align: "center",
            isShow: true,
            render: (text) => {
                if (!text) return <span style={{color: '#9ca3af', fontStyle: 'italic', fontSize: '13px'}}>无描述</span>;
                // 截取前11个字符，超出显示省略号
                const showText = text.length > 11 ? `${text.slice(0, 11)}......` : text;
                return (
                    <Tooltip
                        title={text}
                        placement="top"
                        mouseEnterDelay={0.3}
                        overlayStyle={{
                            maxWidth: '350px',
                            whiteSpace: 'pre-wrap',
                            padding: '8px 12px',
                            borderRadius: '6px'
                        }}
                    >
                        <div style={{
                            color: '#ff007f',
                            cursor: 'help',
                            textOverflow: 'ellipsis',
                            overflow: 'hidden',
                            whiteSpace: 'nowrap',
                            maxWidth: '220px',
                            fontSize: '13px'
                        }}>{showText}</div>
                    </Tooltip>
                );
            }
        }, {
            title: "开启状态",
            dataIndex: "startStatusValue",
            key: "startStatusValue",
            width: 120,
            align: "center",
            isShow: true,
            render: (text) => {
                // 转换枚举值显示（Yes->开启，No->关闭）
                const displayText = text === '是' ? '开启' : '关闭';
                const config = statusConfig.startStatus[text] || statusConfig.startStatus['否'];
                return (
                    <Tag
                        style={{
                            ...baseTagStyle,
                            backgroundColor: config.bgColor,
                            color: config.color
                        }}
                        onMouseEnter={(e) => {
                            e.currentTarget.style.transform = 'scale(1.08)';
                            e.currentTarget.style.boxShadow = `0 2px 8px rgba(0,0,0,0.08)`;
                        }}
                        onMouseLeave={(e) => {
                            e.currentTarget.style.transform = 'scale(1)';
                            e.currentTarget.style.boxShadow = 'none';
                        }}
                    >
                        {config.icon}
                        {displayText}
                    </Tag>
                );
            }
        }, {
            title: "上次执行状态",
            dataIndex: "lastExecuteStatusValue",
            key: "lastExecuteStatusValue",
            width: 140,
            align: 'center',
            isShow: true,
            render: (text) => {
                const config = statusConfig.executeStatus[text] || statusConfig.executeStatus['未执行'];
                return (
                    <Tag
                        style={{
                            ...baseTagStyle,
                            backgroundColor: config.bgColor,
                            color: config.color
                        }}
                        onMouseEnter={(e) => {
                            e.currentTarget.style.transform = 'scale(1.08)';
                            e.currentTarget.style.boxShadow = `0 2px 8px rgba(0,0,0,0.08)`;
                        }}
                        onMouseLeave={(e) => {
                            e.currentTarget.style.transform = 'scale(1)';
                            e.currentTarget.style.boxShadow = 'none';
                        }}
                    >
                        <span style={config.isSpin ? {animation: 'spin 1.5s linear infinite'} : {}}>
                            {config.icon}
                        </span>
                        {text || '未执行'}
                    </Tag>
                );
            }
        }, {
            title: "下次执行时间",
            dataIndex: "nextExecuteTime",
            key: "nextExecuteTime",
            width: 180,
            align: "center",
            isShow: true,
            render: (text) => (
                <div style={{
                    color: '#10b981',
                    fontSize: '13px',
                    fontWeight: 500,
                    padding: '3px 8px',
                    borderRadius: '4px',
                    display: 'inline-block'
                }}>{text || '未设置'}</div>
            )
        }, {
            title: "执行频率",
            dataIndex: "cronDescription",
            key: "cronDescription",
            width: 160,
            align: "center",
            isShow: true,
            render: (text) => (
                <div style={{
                    color: '#4e5969',
                    fontSize: '13px',
                    padding: '2px 8px',
                    borderRadius: '4px'
                }}>{text || '-'}</div>
            )
        }, {
            title: "执行次数",
            dataIndex: "executeCount",
            key: "executeCount",
            width: 100,
            align: 'center',
            isShow: true,
            render: (text) => {
                const count = text || 0;
                // 根据执行次数设置不同颜色
                let color = '#666';
                if (count > 100) color = '#ff4d4f';
                else if (count > 50) color = '#fa8c16';
                else if (count > 0) color = '#1890ff';

                return (
                    <div style={{
                        color,
                        fontSize: '13px',
                        fontWeight: 600,
                        backgroundColor: '#f5f5f5',
                        width: '40px',
                        height: '26px',
                        borderRadius: '13px',
                        display: 'flex',
                        alignItems: 'center',
                        justifyContent: 'center',
                        transition: 'all 0.2s ease'
                    }}
                         onMouseEnter={(e) => {
                             e.currentTarget.style.backgroundColor = '#e8e8e8';
                             e.currentTarget.style.transform = 'scale(1.1)';
                         }}
                         onMouseLeave={(e) => {
                             e.currentTarget.style.backgroundColor = '#f5f5f5';
                             e.currentTarget.style.transform = 'scale(1)';
                         }}>
                        {count}
                    </div>
                );
            }
        }, {
            title: "服务名称",
            dataIndex: "serviceName",
            key: "serviceName",
            width: 140,
            align: "center",
            isShow: true,
            render: (text) => (
                <Tag
                    style={{
                        backgroundColor: 'rgba(72, 187, 120, 0.1)',
                        color: '#36ad47',
                        borderColor: 'rgba(72, 187, 120, 0.2)',
                        borderRadius: '6px',
                        padding: '3px 10px',
                        fontSize: '13px',
                        fontWeight: 500
                    }}
                    onMouseEnter={(e) => {
                        e.currentTarget.style.backgroundColor = 'rgba(72, 187, 120, 0.15)';
                        e.currentTarget.style.transform = 'scale(1.05)';
                    }}
                    onMouseLeave={(e) => {
                        e.currentTarget.style.backgroundColor = 'rgba(72, 187, 120, 0.1)';
                        e.currentTarget.style.transform = 'scale(1)';
                    }}
                >
                    {text}
                </Tag>
            )
        }, {
            title: "回调地址",
            dataIndex: "uri",
            key: "uri",
            width: 240,
            align: "center",
            isShow: true,
            render: (text) => (
                <Tooltip
                    title={text}
                    placement="top"
                    mouseEnterDelay={0.3}
                    overlayStyle={{fontSize: '13px'}}
                >
                    <div style={{
                        fontSize: '13px',
                        textOverflow: 'ellipsis',
                        overflow: 'hidden',
                        whiteSpace: 'nowrap',
                        maxWidth: '240px',
                        cursor: 'pointer',
                        fontFamily: 'SFMono-Regular, Consolas, monospace'
                    }}>{text || '-'}</div>
                </Tooltip>
            )
        }, {
            title: "上次执行时间",
            dataIndex: "lastExecuteTime",
            key: "lastExecuteTime",
            width: 180,
            align: "center",
            isShow: true,
            render: (text) => (
                <div style={{
                    color: '#0066cc',
                    fontSize: '13px',
                    fontWeight: 500,
                    padding: '3px 8px',
                    borderRadius: '4px',
                    display: 'inline-block'
                }}>{text || '无记录'}</div>
            )
        }, {
            title: "id",
            dataIndex: 'id',
            key: 'id',
            align: 'center',
            isShow: false
        }, {
            title: '创建人',
            dataIndex: 'createdByUserNickname',
            key: 'createdByUserNickname',
            width: 120,
            align: 'center',
            isShow: true,
            render: (text) => (
                <div style={{
                    color: '#009999',
                    fontSize: '13px',
                    fontWeight: 500
                }}>{text || '系统'}</div>
            )
        }, {
            title: '创建时间',
            dataIndex: 'createdTime',
            key: 'createdTime',
            width: 180,
            align: 'center',
            isShow: true,
            render: (text) => (
                <div style={{
                    color: '#006666',
                    fontSize: '12px',
                    backgroundColor: 'rgba(0, 102, 102, 0.05)',
                    padding: '2px 6px',
                    borderRadius: '3px'
                }}>{text}</div>
            )
        }, {
            title: '最后编辑人',
            dataIndex: 'lastModifiedByUserNickname',
            key: 'lastModifiedByUserNickname',
            width: 120,
            align: 'center',
            isShow: true,
            render: (text) => (
                <div style={{
                    color: '#004c99',
                    fontSize: '13px',
                    fontWeight: 500
                }}>{text || '系统'}</div>
            )
        }, {
            title: '最后编辑时间',
            dataIndex: 'lastModifiedTime',
            key: 'lastModifiedTime',
            width: 180,
            align: 'center',
            isShow: true,
            render: (text) => (
                <div style={{
                    color: '#004c99',
                    fontSize: '12px',
                    backgroundColor: 'rgba(0, 76, 153, 0.05)',
                    padding: '2px 6px',
                    borderRadius: '3px'
                }}>{text}</div>
            )
        }, {
            title: "操作",
            key: "operation",
            width: 180, // 固定操作列宽度
            align: 'center',
            fixed: 'right', // 关键：固定在右侧
            isShow: true,
            render: (text, record) => (
                <Space size="small">
                    <Button
                        size={"small"}
                        type="text"
                        icon={<EyeOutlined/>}
                        style={{
                            fontSize: '14px',
                            color: '#1890ff',
                            backgroundColor: 'rgba(24, 144, 255, 0.05)',
                            border: '1px solid #91d5ff',
                            borderRadius: '6px',
                            padding: '4px 12px',
                            transition: 'all 0.3s cubic-bezier(0.4, 0, 0.2, 1)',
                            display: 'inline-flex',
                            alignItems: 'center',
                            gap: '4px'
                        }}
                        onMouseEnter={(e) => {
                            e.target.style.backgroundColor = 'rgba(24, 144, 255, 0.1)';
                            e.target.style.transform = 'translateY(-2px)';
                            e.target.style.boxShadow = '0 2px 8px rgba(24, 144, 255, 0.2)';
                        }}
                        onMouseLeave={(e) => {
                            e.target.style.backgroundColor = 'rgba(24, 144, 255, 0.05)';
                            e.target.style.transform = 'translateY(0)';
                            e.target.style.boxShadow = 'none';
                        }}
                        onClick={() => redirect2TaskDetail('search', record.id)}
                    >
                        查看
                    </Button>
                    <Button
                        size={"small"}
                        type="text"
                        icon={<EditOutlined/>}
                        style={{
                            fontSize: '14px',
                            color: '#fa8c16',
                            backgroundColor: 'rgba(250, 140, 22, 0.05)',
                            border: '1px solid #ffbb96',
                            borderRadius: '6px',
                            padding: '4px 12px',
                            transition: 'all 0.3s cubic-bezier(0.4, 0, 0.2, 1)',
                            display: 'inline-flex',
                            alignItems: 'center',
                            gap: '4px'
                        }}
                        onMouseEnter={(e) => {
                            e.target.style.backgroundColor = 'rgba(250, 140, 22, 0.1)';
                            e.target.style.transform = 'translateY(-2px)';
                            e.target.style.boxShadow = '0 2px 8px rgba(250, 140, 22, 0.2)';
                        }}
                        onMouseLeave={(e) => {
                            e.target.style.backgroundColor = 'rgba(250, 140, 22, 0.05)';
                            e.target.style.transform = 'translateY(0)';
                            e.target.style.boxShadow = 'none';
                        }}
                        onClick={() => redirect2TaskDetail('edit', record.id)}
                    >
                        编辑
                    </Button>
                </Space>
            )
        }
    ];

    /**
     * 分页查询定时任务
     */
    const pageQueryScheduleTask = () => {
        RequestUtils.post(RequestApis.taskManage.page, {
            ...paginationReq,
            ...pageQueryTaskReq
        }).then(res => {
            setPageQueryTaskResp(res.data.data);
        }).catch(err => messageApi.error(err.message))
    }


    /**
     * 重定向到定时任务详情页面
     */
    const redirect2TaskDetail = (type, id) => {
        navigate(`/console/task/${type}/${id}`);
    }

    /**
     * 监听分页查询控件执行分页查询
     */
    useEffect(() => {
        pageQueryScheduleTask();
        // eslint-disable-next-line
    }, [paginationReq]);

    // 表格行样式 - 交替行背景色
    const getRowClassName = (record, index) => {
        return index % 2 === 0 ? 'table-row-even' : 'table-row-odd';
    };

    return (
        <div>
            {contextHolder}

            {/* 全局样式：添加旋转动画 */}
            <style jsx global>{`
                @keyframes spin {
                    from {
                        transform: rotate(0deg);
                    }
                    to {
                        transform: rotate(360deg);
                    }
                }

                .table-row-even {
                    background-color: #fcfcfc;
                }

                .table-row-odd {
                    background-color: #ffffff;
                }

                /* 修复固定列边框问题 */
                .ant-table-fixed-right .ant-table-cell {
                    border-left: 1px solid #f0f0f0 !important;
                }

                /* 优化滚动条样式 */
                ::-webkit-scrollbar {
                    height: 8px;
                    width: 8px;
                }

                ::-webkit-scrollbar-track {
                    background: #f5f5f5;
                    border-radius: 4px;
                }

                ::-webkit-scrollbar-thumb {
                    background: #ccc;
                    border-radius: 4px;
                }

                ::-webkit-scrollbar-thumb:hover {
                    background: #999;
                }
            `}</style>

            {/* 查询条件组件 */}
            <div style={{padding: '16px', paddingBottom: '8px'}}>
                <TaskSearch
                    setPaginationReq={setPaginationReq}
                    pageQueryTaskReq={pageQueryTaskReq}
                    setPageQueryTaskReq={setPageQueryTaskReq}
                    pageQueryScheduleTask={pageQueryScheduleTask}
                />
            </div>

            <div style={{padding: '0 16px 16px'}}>
                <Button
                    type="primary"
                    style={{
                        fontSize: '14px',
                        padding: '6px 16px',
                        borderRadius: '6px',
                        backgroundColor: '#1890ff',
                        borderColor: '#1890ff',
                        transition: 'all 0.2s ease'
                    }}
                    onMouseEnter={(e) => {
                        e.target.style.backgroundColor = '#096dd9';
                        e.target.style.transform = 'translateY(-1px)';
                    }}
                    onMouseLeave={(e) => {
                        e.target.style.backgroundColor = '#1890ff';
                        e.target.style.transform = 'translateY(0)';
                    }}
                    onClick={() => setCreateTaskVisible(true)}
                >
                    <PlusCircleOutlined style={{marginRight: '8px'}}/>
                    新增定时任务
                </Button>
            </div>

            {/* 表格展示（表头固定，内容滚动，操作列固定右侧） */}
            <div style={{
                margin: '0 16px',
                backgroundColor: '#fff',
                borderRadius: '8px',
                boxShadow: '0 2px 8px rgba(0, 0, 0, 0.04)',
                overflow: 'hidden',
                transition: 'box-shadow 0.3s ease'
            }} onMouseOver={(e) => {
                e.currentTarget.style.boxShadow = '0 4px 16px rgba(0, 0, 0, 0.08)';
            }} onMouseOut={(e) => {
                e.currentTarget.style.boxShadow = '0 2px 8px rgba(0, 0, 0, 0.04)';
            }}>
                <Table
                    dataSource={pageQueryTaskResp.records}
                    columns={pageQueryTaskRespFields.filter(item => item.isShow)}
                    pagination={false}
                    scroll={{
                        y: 'calc(100vh - 460px)',
                        x: '100%' // 确保水平滚动生效
                    }}
                    bordered={false}
                    rowHoverable
                    style={{width: '100%'}}
                    tableLayout="fixed" // 固定表格布局，确保列宽生效
                    rowClassName={getRowClassName}
                    headerStyle={{
                        backgroundColor: '#fafafa',
                        color: '#1f2329',
                        fontWeight: 600,
                        fontSize: '14px',
                        borderBottom: '1px solid #e5e6eb',
                        padding: '12px 0',
                        textAlign: 'center'
                    }}
                    bodyStyle={{
                        fontSize: '13px'
                    }}
                    rowStyle={{
                        height: '60px',
                        transition: 'background-color 0.2s ease'
                    }}
                    // 添加表格加载状态
                    loading={{
                        spinning: false, // 可以根据实际加载状态设置
                        indicator: <div style={{padding: '40px 0'}}>加载中...</div>
                    }}
                    // 表格行悬停样式
                    onRow={(record, index) => ({
                        onMouseEnter: (e) => {
                            e.currentTarget.style.backgroundColor = 'rgba(0, 0, 0, 0.02)';
                        },
                        onMouseLeave: (e) => {
                            const isEven = index % 2 === 0;
                            e.currentTarget.style.backgroundColor = isEven ? '#fcfcfc' : '#fff';
                        },
                    })}
                    // 修复固定列与滚动列的对齐问题
                    columnWidth={column => {
                        if (column.fixed) return column.width;
                        return column.width || 120;
                    }}
                />
            </div>

            {/* 分页组件 */}
            <div style={{
                display: "flex",
                justifyContent: "flex-end",
                alignItems: "center",
                height: '60px',
                margin: '8px 16px 0',
                fontSize: '13px'
            }}>
                <Pagination
                    total={pageQueryTaskResp.total}
                    current={paginationReq.pageNum}
                    pageSize={paginationReq.pageSize}
                    showSizeChanger
                    showQuickJumper
                    showTotal={(total) => {
                        return (
                            <div style={{fontSize: '13px', marginRight: '16px'}}>
                                <span>共</span>
                                <span style={{color: '#1890ff', fontWeight: 'bold'}}> {total} </span>
                                <span>条数据</span>
                            </div>
                        )
                    }}
                    pageSizeOptions={['10', '20', '50', '100', '200']}
                    onChange={(pageNum, pageSize) => {
                        setPaginationReq({
                            ...paginationReq,
                            pageNum: pageNum,
                            pageSize: pageSize
                        })
                    }}
                    onShowSizeChange={(current, size) => {
                        setPaginationReq({
                            ...paginationReq,
                            pageNum: current,
                            pageSize: size
                        })
                    }}
                    style={{
                        padding: '8px 0'
                    }}
                    itemStyle={{
                        borderRadius: '4px',
                        margin: '0 2px',
                        transition: 'all 0.2s ease'
                    }}
                    prevIcon={<span style={{transition: 'transform 0.2s ease'}}>←</span>}
                    nextIcon={<span style={{transition: 'transform 0.2s ease'}}>→</span>}
                    // 分页按钮悬停效果
                    onItemHover={(value, type, hover) => {
                        const items = document.querySelectorAll('.ant-pagination-item, .ant-pagination-prev, .ant-pagination-next');
                        items.forEach(item => {
                            if (hover) {
                                item.style.transform = 'translateY(-1px)';
                                item.style.boxShadow = '0 2px 4px rgba(0,0,0,0.1)';
                            } else {
                                item.style.transform = 'translateY(0)';
                                item.style.boxShadow = 'none';
                            }
                        });
                    }}
                />
            </div>

            {/* 创建定时任务模态框 */}
            <TaskCreate
                visible={createTaskVisible}
                setVisible={setCreateTaskVisible}
                pageQueryScheduleTask={pageQueryScheduleTask}
            />
        </div>
    );
}

export default ConsoleTaskPage;